package com.zc.gateway.security.manager;

import com.zc.commons.auth.dto.LoginUserDetails;
import com.zc.gateway.entity.LoginEntity;
import com.zc.gateway.infra.service.LoginUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class LoginAuthenticationManager implements ReactiveAuthenticationManager {

    @Autowired
    private LoginUserDetailsService loginUserDetailsService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {

        LoginEntity principal = (LoginEntity) authentication.getPrincipal();

        LoginUserDetails details = loginUserDetailsService.queryUserDetailsByAccount(principal.getUserAccount());
        if (details == null) {
            return Mono.error(new UsernameNotFoundException(String.format("账号[%s]不存在！", principal.getUserAccount())));
        }
        if (bCryptPasswordEncoder.matches(principal.getPassword(), details.getPassword())) {
            return Mono.error(new UsernameNotFoundException("密码错误！"));
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(details, null);
        return Mono.just(authenticationToken);
    }
}
